<template>
  <div style="background: #fff">
    <a-tabs @change="selectTabs">
      <a-tab-pane key="orderConfig" tab="系统配置">
        <div v-if="vdata.groupKey == 'orderConfig'" class="account-settings-info-view">
          <a-form ref="configFormModel" :model="vdata.mchConfigData" layout="vertical">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-col v-for="(item, config) in vdata.mchConfigData" :key="config" :span="7" :offset="1">
                <a-form-item :label="item.configName">
                  <a-radio-group v-if="item.type === 'radio'" v-model:value="item.configVal">
                    <a-radio value="1">启用</a-radio>
                    <a-radio value="0">禁用</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button :disabled="!$access('ENT_MCH_CONFIG_EDIT')" type="primary" :loading="vdata.btnLoading" @click="confirm"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="mchLevel" tab="功能配置">
        <div v-if="vdata.groupKey == 'mchLevel'" class="account-settings-info-view" style="margin-left: 40px">
          <a-form layout="vertical">
            <a-row justify="start" type="flex" style="margin-top: 20px">
              <a-form-item label="商户等级切换">
                <div class="typePopover">
                  <a-popover placement="top">
                    <template #title><span>商户级别</span></template>
                    <template #content>
                      <p>M0商户：简单模式（页面简洁，仅基础收款功能）</p>
                      <p>M1商户：高级模式（支持api调用， 支持配置应用及分账、转账功能）</p>
                    </template>
                    <question-circle-outlined />
                  </a-popover>
                </div>
                <a-radio-group v-model:value="vdata.mchLevel">
                  <a-radio value="M0">M0</a-radio>
                  <a-radio value="M1">M1</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-row>
            <a-form-item class="bottom-btn">
              <a-button :disabled="!$access('ENT_MCH_CONFIG_EDIT')" type="primary" :loading="vdata.btnLoading" @click="confirmUpdateLevel"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>


      <a-tab-pane v-if="userStore.userInfo.mchLevel == 'M1'" key="payOrderNotifyExtParams" tab="回调和查单参数">
        <div v-if="vdata.groupKey == 'payOrderNotifyExtParams'" class="account-settings-info-view" style="margin-left: 40px">
          <a-form :label-col="{span: 2}" :wrapper-col="{span: 12}">
            <a-form-item label="POS支付回调地址" name="mchPayNotifyUrl">
              <a-input v-model:value="vdata.mchPayNotifyUrl" />
            </a-form-item>
            <a-form-item label="POS退款回调地址" name="mchRefundNotifyUrl">
              <a-input v-model:value="vdata.mchRefundNotifyUrl" />
              <div class="jeepay-tip-text">
                <p>智能POS收款、退款等场景下，需要配置商户回调地址</p>
                <p>接口下单以下单传参为准</p>
              </div>
            </a-form-item>

            <a-form-item>
              <template #label>
                <span>回调方式</span> &nbsp;
                <a-popover placement="top">
                  <template #title><span>回调方式</span></template>
                  <template #content>
                    <p>设置后该商户接收支付网关所有的通知（支付、退款等回调）将全部以此方式发送。</p>
                    <p>POST(Body形式)： method: POST; Content-Type: application/x-www-form-urlencoded; 回调参数（ 例如a=1&b=2 ）放置在Body 发送。</p>
                    <p>POST(QueryString形式)： method: POST; Content-Type: application/x-www-form-urlencoded; 回调参数（ 例如a=1&b=2 ）放置在QueryString 发送。</p>
                    <p>POST(JSON形式)： method: POST; Content-Type: application/json; 回调参数（ 例如{a: 1, b: 2} ）放置在Body 发送。</p>
                  </template>
                  <question-circle-outlined />
                </a-popover>
                   &nbsp;
              </template>
              <a-radio-group v-model:value="vdata.mchNotifyPostType">
                <a-radio value="POST_BODY">POST(Body 形式)</a-radio>
                <a-radio value="POST_QUERYSTRING">POST(QueryString 形式)</a-radio>
                <a-radio value="POST_JSON">POST(JSON 形式)</a-radio>
              </a-radio-group>
            </a-form-item>
              
            <a-table :dataSource="vdata.notifyTableData" :columns="vdata.notifyTableColumns" :pagination="false" size="small">
              <!-- header 标题 插槽 -->
              <template #headerCell="{ column }">
                <template v-if="column.key === 'batch'">
                  <a-checkbox @change="(e) => notifyAllCehcked(e.target.checked)" />
                </template>
              </template>

              <template #bodyCell="{ column, record }">
                <template v-if="column.key === 'batch'"><a-checkbox v-model:checked="record.checked" :disabled="record.disabled" /></template>
                <template v-if="column.key === 'wayName'">{{ record.wayName }}[{{ record.wayCode }}]</template>
              </template>

              <template #title>回调参数配置</template>
            </a-table>


            <a-form-item class="bottom-btn">
              <a-button :disabled="!$access('ENT_MCH_CONFIG_EDIT')" type="primary" :loading="vdata.btnLoading" @click="confirmByNotify"><check-circle-outlined />确认更新</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="divisionManage" tab="分账管理">
        <div v-if="vdata.groupKey == 'divisionManage' && vdata.divisionConfig.mchDivisionEntFlag == 0" style="height: 200px">
          <a-divider orientation="left"><info-circle-outlined /> 当前没有可配置的选项</a-divider>
        </div>
        <div v-if="vdata.groupKey == 'divisionManage' && vdata.divisionConfig.mchDivisionEntFlag == 1" class="account-settings-info-view" style="margin-top: 20px">
          <a-form :label-col="{ span: 4 }" :wrapper-col="{ span: 12 }">
            <a-form-item>
              <template #label>
                <span>全局自动分账</span> &nbsp;
                <a-popover placement="top">
                  <template #title><span>全局自动分账</span></template>
                  <template #content>
                    <p>开启：将根据[全局自动分账规则]进行自动分账处理（屏蔽下单API的分账参数， 订单标识都是自动分账模式）</p>
                    <p>关闭：以API传参为准</p>
                  </template>
                  <question-circle-outlined />
                </a-popover>
                   &nbsp;
              </template>
              <a-radio-group v-model:value="vdata.divisionConfig.overrideAutoFlag">
                <a-radio :value="1">开启</a-radio>
                <a-radio :value="0">关闭</a-radio>
              </a-radio-group>
            </a-form-item>

            <div v-if="vdata.divisionConfig.overrideAutoFlag == 1" style="margin-left: 50px">
              <a-divider orientation="left">全局自动分账规则</a-divider>

              <a-form-item label="金额限制">
                <span style="line-height: 30px;">当订单金额大于等于 &nbsp;</span>
                <a-input-number v-model:value="vdata.divisionConfig.autoDivisionRules.amountLimit" :min="0" :precision="2" style="width:140px">
                  <template #addonAfter>元</template>
                </a-input-number>
                <span style="line-height: 30px;"> &nbsp;时自动分账</span>
              </a-form-item>

              <a-form-item label="自动分账时间">
                订单支付成功： <a-select v-model:value="vdata.divisionConfig.autoDivisionRules.delayTime" style="width: 110px" placeholder="时间">
                  <a-select-option :value=" (2 * 60) ">2分钟</a-select-option>
                  <a-select-option :value=" (5 * 60) ">5分钟</a-select-option>
                  <a-select-option :value=" (10 * 60) ">10分钟</a-select-option>
                  <a-select-option :value=" (30 * 60) ">30分钟</a-select-option>
                  <a-select-option :value=" (60 * 60) ">1小时</a-select-option>
                  <a-select-option :value=" (2 * 60 * 60) ">2小时</a-select-option>
                </a-select> 后
              </a-form-item>
            </div>

            <a-form-item class="bottom-btn">
              <a-button type="primary" :loading="vdata.btnLoading" @click="confirmByDivisionManage"><check-circle-outlined />保存</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>

      <a-tab-pane key="securityConfig" tab="安全管理">
        <div v-if="vdata.groupKey == 'securityConfig'">
          <a-form ref="sipwFormModel" :model="vdata.sipwObject" :label-col="{span: 3}" :wrapper-col="{span: 6}" :rules="sipwRules">
            <a-form-item v-if="vdata.sipwObject.isShow" label="原支付密码：" name="originalPwd">
              <a-input-password v-model:value="vdata.sipwObject.originalPwd" maxlength="6" autocomplete="new-password" placeholder="请输入原密码" />
            </a-form-item>
            <a-form-item label="新支付密码：" name="newPwd">
              <a-input-password v-model:value="vdata.sipwObject.newPwd" maxlength="6" autocomplete="new-password" placeholder="请输入新密码" />
            </a-form-item>
            <a-form-item label="确认新支付密码：" name="confirmPwd">
              <a-input-password v-model:value="vdata.sipwObject.confirmPwd" maxlength="6" autocomplete="new-password" placeholder="确认新密码" />
            </a-form-item>
            <a-form-item class="bottom-btn">
              <a-button :disabled="!$access('ENT_MCH_CONFIG_EDIT')" type="primary" :loading="vdata.btnLoading" @click="confirmUpdateSipw"><check-circle-outlined />确认更改</a-button>
            </a-form-item>
          </a-form>
        </div>
      </a-tab-pane>
    </a-tabs>
  </div>
</template>
<script setup lang="ts">
import { API_URL_MCH_CONFIG, req, $getMainUserInfo, $updateMchLevel, $updateMchSipw, $isSipw } from '@/api/manage'
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useUserStore } from '@/store/modules/user'

// store对象
const userStore = useUserStore()

const { $infoBox, $access } = getCurrentInstance()!.appContext.config.globalProperties

const configFormModel = ref()

const sipwFormModel = ref()

const sipwRules = {
  originalPwd: [{ required: true, pattern: /^\d{6}$/, message: '请输入原密码(6位数字格式)', trigger: 'blur' }],
  newPwd: [{ required: true, pattern: /^\d{6}$/, message: '请输入新支付密码(6位数字格式)', trigger: 'blur' }],
  confirmPwd: [
      { required: true, trigger: 'blur', validator: (rule, value) => {
          if(vdata.sipwObject.newPwd != value){
            return Promise.reject('新密码与确认新密码不一致')
          }
          return Promise.resolve()
        },
      }
    ],
}

const vdata : any = reactive ({
  btnLoading: false,
  groupKey: 'orderConfig',
  mchConfigData: [] as any, // 配置保存对象
  defaultConfig: [
  {
    configKey: 'appVoice',
    configName: '是否启用app订单语音播报',
    configVal: '1',
    type: 'radio'
  },
  {
    configKey: 'weChatVoice',
    configName: '是否启用小程序订单语音播报',
    configVal: '1',
    type: 'radio'
  },
   {
    configKey: 'qrcEscaping',
    configName: '是否启用码牌防逃单功能',
    configVal: '1',
    type: 'radio'
  }
], // 默认配置项

  mchLevel: '',

  mchPayNotifyUrl: '', // 商户支付回调地址
  mchRefundNotifyUrl: '', // 商户退款回调地址
  mchNotifyPostType: 'POST_BODY', // 发送商户通知的方式  POST_BODY   POST_QUERYSTRING  POST_JSON
  notifyTableColumns: [
    {key: 'batch', title: '批量选择' },
    {key: 'key', dataIndex: 'key', title: '参数KEY' },
    {key: 'name', dataIndex: 'name', title: '参数名称' },
    // {key: 'desc', dataIndex: 'desc', title: '参数描述' }
  ],

  notifyTableData: [
    {key: 'payOrderId', name: '支付订单号', desc: '', checked: true, disabled: true },
    {key: 'mchNo', name: '商户号', desc: '商户号', checked: true, disabled: true },
    {key: 'appId', name: '应用ID', desc: '', checked: true, disabled: true },
    {key: 'mchOrderNo', name: '商户订单号', desc: '', checked: true, disabled: true },
    {key: 'ifCode', name: '支付接口', desc: '', checked: true, disabled: true },
    {key: 'wayCode', name: '支付方式', desc: '', checked: true, disabled: true },
    {key: 'amount', name: '支付金额', desc: '', checked: true, disabled: true },
    {key: 'currency', name: '货币代码', desc: '', checked: true, disabled: true },
    {key: 'state', name: '订单状态', desc: '', checked: true, disabled: true },
    {key: 'clientIp', name: '客户端IP', desc: '', checked: true, disabled: true },
    {key: 'subject', name: '商品标题', desc: '', checked: true, disabled: true },
    {key: 'body', name: '商品描述', desc: '', checked: true, disabled: true },
    {key: 'channelOrderNo', name: '渠道订单号', desc: '', checked: true, disabled: true },
    {key: 'errCode', name: '渠道错误码', desc: '', checked: true, disabled: true },
    {key: 'errMsg', name: '渠道错误描述', desc: '', checked: true, disabled: true },
    {key: 'extParam', name: '扩展参数', desc: '', checked: true, disabled: true },
    {key: 'successTime', name: '支付成功时间', desc: '', checked: true, disabled: true },
    {key: 'createdAt', name: '创建时间', desc: '', checked: true, disabled: true },
    {key: 'sign', name: '签名', desc: '', checked: true, disabled: true },

    {key: 'storeId', name: '门店ID', desc: '', checked: false, disabled: false },
    {key: 'lng', name: '经度', desc: '', checked: false, disabled: false },
    {key: 'lat', name: '纬度', desc: '', checked: false, disabled: false },
    {key: 'qrcId', name: '码牌ID', desc: '', checked: false, disabled: false },
    {key: 'wayCodeType', name: '支付方式代码分类', desc: '', checked: false, disabled: false },
    {key: 'mchFeeRate', name: '商户手续费费率快照', desc: '', checked: false, disabled: false },
    {key: 'mchFeeAmount', name: '商户手续费,单位分', desc: '', checked: false, disabled: false },
    {key: 'channelUser', name: '渠道用户标识,如微信openId,支付宝账号', desc: '', checked: false, disabled: false },
    {key: 'divisionMode', name: '订单分账模式', desc: '', checked: false, disabled: false },
    {key: 'buyerRemark', name: '买家备注', desc: '买家备注', checked: false, disabled: false },
    {key: 'sellerRemark', name: '卖家备注', desc: '卖家备注', checked: false, disabled: false },
    {key: 'expiredTime', name: '订单失效时间', desc: '', checked: false, disabled: false },
  ],

  sipwObject:{ }, // 支付密码保存对象

  // 分账管理菜单 
  divisionConfig: { overrideAutoFlag: 0, autoDivisionRules: { amountLimit: 0, delayTime: 120  }, mchDivisionEntFlag: 1, calBaseAmountType: 'INCOME_AMOUNT' },

})
const  isSipw = ()=>{
  $isSipw().then((res)=>{
    vdata.sipwObject.isShow = res
  })
}
onMounted(()=>{
  selectTabs(vdata.groupKey) //初始化数据
  isSipw()
})


function selectTabs (key) { // 清空必填提示
  if (key) {
    vdata.groupKey = key

    if(key == 'orderConfig'){

      req.list(API_URL_MCH_CONFIG, {groupKey: vdata.groupKey}).then(res => {
        if (res != null && res.length > 0) {
          vdata.mchConfigData = res
        }else {
          vdata.mchConfigData = vdata.defaultConfig
        }
      })
    }else if(key == 'payOrderNotifyExtParams'){

        // 恢复初始值
      vdata.notifyTableData.filter(r => !r.disabled).forEach(r => {
          r. checked = false
      })
      vdata.mchNotifyPostType = 'POST_BODY'
      vdata.mchPayNotifyUrl = ''
      vdata.mchRefundNotifyUrl = ''

      req.list(API_URL_MCH_CONFIG, {groupKey: vdata.groupKey}).then(res => {
        if (res != null && res.length > 0) {
          res.forEach(item => {
            if (item.configKey == 'payOrderNotifyExtParams') {
              let arr = JSON.parse(item.configVal)
              vdata.notifyTableData.filter(r => !r.disabled).forEach(r => {
                r. checked =  arr.indexOf(r.key) >= 0
              })
            }else if (item.configKey == 'mchPayNotifyUrl') {
                vdata.mchPayNotifyUrl = item.configVal
              }else if (item.configKey == 'mchRefundNotifyUrl') {
                vdata.mchRefundNotifyUrl = item.configVal
              }else if (item.configKey == 'mchNotifyPostType') {
                vdata.mchNotifyPostType = item.configVal
              }
          })
        }
      })
    }else if(key == 'mchLevel'){
      
      $getMainUserInfo().then((res) => {
        vdata.mchLevel = res.mchLevel
      })
    }else if(key == 'divisionManage'){
      
      // 分账管理恢复默认
      vdata.divisionConfig = { overrideAutoFlag: 0, autoDivisionRules: { amountLimit: 0, delayTime: 120  }, mchDivisionEntFlag: 1, calBaseAmountType: 'INCOME_AMOUNT' }

      req.list(API_URL_MCH_CONFIG, {groupKey: vdata.groupKey, mchNo: vdata.recordId}).then(res => {
        if (res != null && res.length > 0) {
          vdata.divisionConfig = JSON.parse(res[0].configVal)
          if(!vdata.divisionConfig.calBaseAmountType){
              vdata.divisionConfig.calBaseAmountType = 'INCOME_AMOUNT' // 存量数据为空， 默认为： 入账金额。 
            }
          vdata.divisionConfig.autoDivisionRules.amountLimit = Number.parseFloat((vdata.divisionConfig.autoDivisionRules.amountLimit / 100).toFixed(2))
        }
      })
    }

  }
}


// 确认更新
function confirm (e) {
  configFormModel.value.validate().then(valid => {
    $infoBox.confirmPrimary('确认修改系统配置吗？', '', () => {
      vdata.btnLoading = true // 打开按钮上的 loading

      let reqObject : any = JSON.parse(JSON.stringify(vdata.mchConfigData))

      req.updateById(API_URL_MCH_CONFIG, vdata.groupKey, {configData: reqObject}).then(res => {
        $infoBox.message.success('修改成功')
        vdata.btnLoading = false
      }).catch(res => {
        vdata.btnLoading = false
      })
    })
  })
}


// 确认更新
function confirmByNotify (e) {

  $infoBox.confirmPrimary('确认修改回调参数吗？', '更新完成后请尽快检查回调接收地址，避免验签失败造成业务损失！', () => {
    vdata.btnLoading = true // 打开按钮上的 loading


    let arr : any = []
    vdata.notifyTableData.filter(r => !r.disabled).forEach(r => {
        if(r.checked){
          arr.push(r.key)
        }
    })

    let configItem = [{ groupKey: vdata.groupKey, configName: '支付订单回调和查单参数', configKey: 'payOrderNotifyExtParams', configVal : JSON.stringify(arr) },
                                  { groupKey: vdata.groupKey, configName: 'POS支付回调地址', configKey: 'mchPayNotifyUrl', configVal : vdata.mchPayNotifyUrl },
                                  { groupKey: vdata.groupKey, configName: 'POS退款回调地址', configKey: 'mchRefundNotifyUrl', configVal : vdata.mchRefundNotifyUrl },
                                  { groupKey: vdata.groupKey, configName: '商户接收通知方式', configKey: 'mchNotifyPostType', configVal : vdata.mchNotifyPostType }

                                ]

    req.updateById(API_URL_MCH_CONFIG, vdata.groupKey, {configData: JSON.stringify(configItem)}).then(res => {
      $infoBox.message.success('修改成功')
      vdata.btnLoading = false
    }).catch(res => {
      vdata.btnLoading = false
    })
  })
}


// 更新商户等级
function confirmUpdateLevel(){
  $updateMchLevel(vdata.mchLevel).then(() => {
    $infoBox.modalWarning('提示', '更新成功，重新登录后将切换功能模式！')
  })
}


// 全选，反选
function notifyAllCehcked(isChekced){
    vdata.notifyTableData.filter(r => !r.disabled).forEach(r => {
      r.checked = isChekced
    })
}


// 更新支付密码
function confirmUpdateSipw(){

  sipwFormModel.value.validate().then(() => {
    return $updateMchSipw(vdata.sipwObject.originalPwd, vdata.sipwObject.confirmPwd)
  }).then((res) => {
     $infoBox.message.success('更新成功')
  })
}

function confirmByDivisionManage(){

  $infoBox.confirmPrimary('确认修改分账设置？', '', () => {
    vdata.btnLoading = true // 打开按钮上的 loading

    let reqObject : any = JSON.parse(JSON.stringify(vdata.divisionConfig))
    reqObject.autoDivisionRules.amountLimit = Number.parseInt((reqObject.autoDivisionRules.amountLimit * 100) + '')

    req.updateById(API_URL_MCH_CONFIG, vdata.groupKey, {mchNo: vdata.recordId, configData: [{configKey: 'divisionConfig', configName: '分账管理', configVal: JSON.stringify(reqObject)}]}).then(res => {
      $infoBox.message.success('修改成功')
      vdata.btnLoading = false
    }).catch(res => {
      vdata.btnLoading = false
    })
  })

}


</script>
<style lang="less" scoped>
  .bottom-btn{
    /deep/ div{
      display: flex;
      justify-content: center;
    }
  }
  .typePopover {
  position: absolute;
  top: -30px;
  left: 93px;
}
</style>
